from fastapi import APIRouter, Depends
from typing import Dict, Any
from ..models.models import EvaluationCreate
from ..utils.decorators import get_current_student
from ..utils.db import call_procedure, execute_update, execute_query
from ..utils.response import APIResponse

router = APIRouter(prefix="/student", tags=["student"])

@router.get("/classes")
async def get_student_classes(current_user: Dict[str, Any] = Depends(get_current_student)):
    """获取学生选课列表"""
    try:
        # 调用存储过程获取未评价课程
        unevaluated_classes, _ = call_procedure("GetStudentUnevaluatedClasses", (current_user["id"],))
        
        # 调用存储过程获取已评价课程  
        evaluated_classes, _ = call_procedure("GetStudentEvaluatedClasses", (current_user["id"],))
        
        # 合并结果并添加评价状态
        all_classes = []
        
        for cls in unevaluated_classes:
            cls["evaluated"] = False
            all_classes.append(cls)
        
        for cls in evaluated_classes:
            cls["evaluated"] = True
            all_classes.append(cls)
        
        return APIResponse.success(all_classes, "获取课程列表成功")
    
    except Exception as e:
        return APIResponse.error(f"获取课程列表失败: {str(e)}", 500)

@router.post("/evaluate")
async def evaluate_class(
    evaluation: EvaluationCreate,
    current_user: Dict[str, Any] = Depends(get_current_student)
):
    """学生评价课程"""
    try:
        # 检查是否是当前用户的评价
        if evaluation.student_id != current_user["id"]:
            return APIResponse.error("只能评价自己选的课程", 403)
        
        # 验证class_id是否存在且学生已选课
        check_query = """
        SELECT sc.StudentID FROM StudentClass sc
        WHERE sc.StudentID = %s AND sc.ClassID = %s
        """
        selected_classes = execute_query(check_query, (evaluation.student_id, evaluation.class_id))
        
        if not selected_classes:
            return APIResponse.error("未选择该课程或课程不存在", 400)
        
        # 检查是否已经评价过
        existing_eval_query = """
        SELECT EvaluationID FROM Evaluation 
        WHERE StudentID = %s AND ClassID = %s
        """
        existing_evals = execute_query(existing_eval_query, (evaluation.student_id, evaluation.class_id))
        
        if existing_evals:
            return APIResponse.error("已经评价过该课程", 400)
        
        # 验证评分范围
        if not (1 <= evaluation.score <= 5):
            return APIResponse.error("评分必须在1-5之间", 400)
        
        # 插入评价
        insert_query = """
        INSERT INTO Evaluation (StudentID, ClassID, Score, Comment, EvaluationTime)
        VALUES (%s, %s, %s, %s, NOW())
        """
        
        affected_rows = execute_update(
            insert_query, 
            (evaluation.student_id, evaluation.class_id, evaluation.score, evaluation.comment)
        )
        
        if affected_rows and affected_rows > 0:
            return APIResponse.success(
                {"evaluation_id": affected_rows}, 
                "评价提交成功"
            )
        else:
            return APIResponse.error("评价提交失败", 500)
    
    except Exception as e:
        # 根据不同错误类型返回不同消息
        error_msg = str(e)
        if "Duplicate entry" in error_msg:
            return APIResponse.error("已经评价过该课程", 400)
        elif "foreign key constraint" in error_msg.lower():
            return APIResponse.error("课程或学生信息不存在", 400)
        else:
            return APIResponse.error(f"评价提交失败: {error_msg}", 500)

@router.get("/evaluations")
async def get_student_evaluations(current_user: Dict[str, Any] = Depends(get_current_student)):
    """获取学生已提交的评价列表"""
    try:
        # 调用存储过程获取已评价课程
        evaluated_classes, _ = call_procedure("GetStudentEvaluatedClasses", (current_user["id"],))
        
        return APIResponse.success(evaluated_classes, "获取评价列表成功")
    
    except Exception as e:
        return APIResponse.error(f"获取评价列表失败: {str(e)}", 500) 